<template>
  <!--el-card:shadow 阴影设置   body-style:设置内容样式 -->
  <el-card shadow="hover" :body-style="{ padding: '20px' }">
    <!-- 添加品牌的按钮 -->
    <el-button type="primary" size="default" :icon="Plus" @click="addTradeMark" v-visite="'btn.Trademark.add'">添加</el-button>

    <!-- 表格:展示品牌数据 
       el-table:表格组件容器   data：能决定表格展示数据有几个
         el-table-column:子组件  type:能决定这一列是什么形态的
         

    -->
    <el-table border  style="margin: 10px 0px" :data="tmObj.records" v-loading="loading" element-loading-text="努力加载中..."
      element-loading-background="rgba(122, 122, 122, 0.2)">
      <el-table-column label="序号" width="80px" align="center" type="index">
      </el-table-column>
      <el-table-column label="品牌名称" prop="tmName"> </el-table-column>
      <el-table-column label="品牌LOGO">
        <template #="{ row, $index }">
          <a :title="row.tmName">
            <img :src="row.logoUrl" alt="" style="width: 100px; height: 60px; border-radius: 10px" />
          </a>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #="{ row, $index }">
          <el-button type="warning" size="small" :icon="Edit" @click="updateTradeMark(row)"></el-button>
          <el-popconfirm
          :title="`你确定删除${row.tmName}?`"
          width="250px"
          :icon="Delete"
          @confirm="deleteTradeMark(row)"
        >
          <template #reference>
            <el-button type="danger" size="small" :icon="Delete"></el-button>
          </template>
        </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 
       v-model:current-page:决定分页器当前第几页
       v-model:page-size,展示几条数据
       total:设置分页总共数据条数
       page-sizes:设置下拉框里面选择数据的条数
       pager-count:可以设置分页器能看见按钮总个数
       current-change:当前页码发生变化的事件回调
       size-change:当选择每一页展示几个数据的时候(下拉框)发生变化的时候会触发
    -->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="tmObj.total"
      :page-sizes="[3,5,7]" background :pager-count="7" layout="prev, pager, next, jumper,->,sizes,total"
      @current-change="getTradeMarkList" @size-change="sizeHandler">
    </el-pagination>


    <!-- 添加或修改 -->
    <!-- Form -->
    <el-dialog v-model="dialogFormVisible" draggable :title="tmParams.id?'修改品牌':'添加品牌'">
      <el-form style="width:80%" label-width="auto" :rules="rules" :model="tmParams" ref="formRef">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input autocomplete="off" v-model="tmParams.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="tmParams.logoUrl" :src="tmParams.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addOrUpdate">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
//引入请求函数
import { reqTradeMarkList, reqAddOrUpdateTradeMark, reqDeleteTradeMark } from "../../../api/product/trademark/trademark";

import { ElMessage } from 'element-plus'

import type { UploadProps, FormInstance, FormRules } from 'element-plus'
//引入element-plus提供icon图标组件
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
  Plus,
} from "@element-plus/icons-vue";
import { ref, onMounted, reactive, nextTick } from "vue";
//引入数据类型
import type { trademarkResponseData, trademark } from '../../../api/product/trademark/model/trademark'
//保存分页器当前页码[当前第几页]
let currentPage = ref<number>(1);
//保存当前页面显示几条数据
let pageSize = ref<number>(3);
//定义控制loding效果响应式数据
let loading = ref<boolean>(false)
//储存组件实例em-form
let formRef = ref<FormInstance>();
//收集新增品牌数据，将来发送请求携带给服务器
let tmParams = reactive<trademark>({
  tmName: '',
  logoUrl: '',
})
//定义接受服务器返回的品牌数据:total|records
let tmObj = reactive<trademarkResponseData>({
  total: 0,
  records: [],
});
let dialogFormVisible = ref<boolean>(false)
//组件挂载完毕需要先获取一次品牌数据:第一页、三条数据
onMounted(() => {
  //先获取一次品牌数据
  getTradeMarkList(1);
});
//专门获取品牌数据的函数
//由于当前函数作为分页器的回调函数:人家底层会注入当前页码
const getTradeMarkList = async (page: number = 1) => {
  //发请求之前loading加载
  loading.value = true;
  //参数整理一下
  currentPage.value = page;
  //再次发请求
  let result = await reqTradeMarkList(currentPage.value, pageSize.value);
  //保存服务器返回的数据
  tmObj.total = result.total; //数据总条数
  tmObj.records = result.records; //品牌的数据
  //服务器数据回来loading效果没有
  loading.value = false;
};

//右边下拉菜单修改一页展示几条数据的回调
const sizeHandler = (limit: number) => {
  //整理参数
  pageSize.value = limit;
  //再次发请求
  getTradeMarkList();
};

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  tmParams.logoUrl = response.data
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/gif') {
    if (rawFile.size / 1024 / 1024 <= 5) {
      return true
    }
  } else {
    return false
  }
}


//确定按钮的回调
const addOrUpdate = async () => {
  //触发el-form组件实例的validate方法
  //全部字段进行验证
  formRef.value?.validate(async (success) => {
    //如果全部校验成功
    if (success) {
      //添加品牌或者修改品牌的请求
      await reqAddOrUpdateTradeMark(tmParams);
      //对话框关闭
      dialogFormVisible.value = false;
      //再次获取最新的全部品牌的数据
      //如果是新增品牌分页器留在第一页，如果是修改留在当前页面
      getTradeMarkList(tmParams.id ? currentPage.value : 1);
      //添加成功显示文字信息
      ElMessage({
        type: 'success',
        message: tmParams.id ? '修改品牌成功' : '添加品牌成功'
      })
    } else {
      //添加失败显示文字信息
      ElMessage({
        type: 'error',
        message: '添加品牌失败'
      })
    }
  })
};



//点击添加按钮清空对话框的数据
const addTradeMark = () => {
  
  dialogFormVisible.value = true,
    tmParams.logoUrl = '',
    tmParams.tmName = ''
  tmParams.id = ''


  //使用nextTick解决校验bug，当响应式数据发生变化，页面重新渲染的时候，获取更新后的DOM
  nextTick(() => {
    formRef.value?.resetFields();
  });
};

//点击修改获取数据，更新数据
const updateTradeMark = (row: trademark) => {
  dialogFormVisible.value = true,
    nextTick(() => {
      formRef.value?.resetFields();

      tmParams.id = row.id,
        tmParams.logoUrl = row.logoUrl,
        tmParams.tmName = row.tmName
    });

};

// 表单验证
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '亲爱的品牌名字不能为空', trigger: 'blur' },
    {
      required: true,
      min: 2,
      max: 10,
      message: "亲爱的品牌名称2-10",
      trigger: "change",
    },
  ],
  logoUrl: [{ required: true, message: '请上传logo图片' }]
});

//删除当前信息
const deleteTradeMark = async (row: trademark) => {
  try {
    await reqDeleteTradeMark(row.id);
    //提示信息
    ElMessage({
      type: "success",
      message: `删除${row.tmName}成功`,
    });
    //再次获取最新数据
    getTradeMarkList(currentPage.value);
  } catch (error) { }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
  
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>